const Service = require('egg').Service;
const lodash = require('lodash');
class GenService extends Service {
    /**
     * 获取表列表
     * @param {*} tablename 
     */
    async tablelist(query) {
        const { ctx, app } = this;
        console.log(query);
        let { page, pageSize, queryParams } = query;
        let { tablename } = queryParams;
        pageSize = pageSize || 10;
        page = page || 1;
        //构建查询sql
        let querySql = "";
        let replacements = [];
        if (!await app.utils.validator.isEmpty(tablename)) {
            querySql = querySql + "AND (table_name LIKE ? OR table_comment LIKE ?) ";
            replacements.push(`%${tablename}%`)
            replacements.push(`%${tablename}%`)
        }
        replacements.push((page - 1) * pageSize);
        replacements.push(pageSize * 1);
        //查询列表
        let tables = await ctx.model.query(`select table_name as table_id,table_name, table_comment, create_time, update_time from information_schema.tables
        where table_schema = (select database()) ${querySql} LIMIT ?, ?`,
            { replacements: replacements, raw: true, type: app.Sequelize.QueryTypes.SELECT });
        //查询总数
        let count = await ctx.model.query(`SELECT count(*) as total from information_schema.tables
        where table_schema = (select database()) ${querySql}`,
            { replacements: replacements, raw: true, type: app.Sequelize.QueryTypes.SELECT });

        return {
            list: tables,
            total: count[0].total
        };
    }


    /**
     * 获取表结构
     * @param {*} tablename 
     */
    async tableColumns(tablename) {
        const { ctx, app } = this;
        //查询列表
        let columns = await ctx.model.query(` select * from (select column_name t_column_name, data_type t_data_type, character_maximum_length t_data_type_length, column_comment t_column_comment,is_nullable t_is_nullable,column_key t_column_key,column_default t_column_default,ordinal_position t_ordinal_position,extra t_column_extra from information_schema.columns
            where table_name = '${tablename}' and table_schema = (select database())) tco left join (select * from sys_gen_column sgc where sgc.table_name='${tablename}') gco on tco.t_column_name = gco.column_name order by tco.t_ordinal_position asc`,
            { raw: true, type: app.Sequelize.QueryTypes.SELECT });
        return columns;
    }

    /**
     * 生成代码
     * @param {*} tablename 
     */
    async genCode(tablename,orgpath) {
        //node.js 文件操作对象
        const fs = require('fs');
        const { ctx, app } = this;
        let camelCaseTableName = lodash.camelCase(tablename);
        let camelCaseTableNameFirst = lodash.upperFirst(camelCaseTableName);
        console.log("tablename==", tablename);
        let columns = await ctx.service.generater.tableColumns(tablename);
        console.log("columns=>", columns);
        let savepath = orgpath + "/";
        let fpath = orgpath + "/代码生成";
        //生成 model
        await ctx.service.fs.createFolder(fpath + `/model/${tablename}.js`);
        await fs.writeFileSync(fpath + `/model/${tablename}.js`, await app.utils.generTool.initModel(tablename, columns));
        //生成 service
        await ctx.service.fs.createFolder(fpath + `/service/${tablename}.js`);
        await fs.writeFileSync(fpath + `/service/${tablename}.js`, await app.utils.generTool.initService(tablename, columns));
        //生成 Controller
        await ctx.service.fs.createFolder(fpath + `/controller/${tablename}.js`);
        await fs.writeFileSync(fpath + `/controller/${tablename}.js`, await app.utils.generTool.initController(tablename, columns));
        //生成 router
        await ctx.service.fs.createFolder(fpath + `/controller/${tablename}_router.js`);
        await fs.writeFileSync(fpath + `/controller/${tablename}_router.js`, await app.utils.generTool.initRouter(tablename, columns));
        //生成 api 
        await ctx.service.fs.createFolder(fpath + `/view/api/${camelCaseTableName}Api.js`);
        await fs.writeFileSync(fpath + `/view/api/${camelCaseTableName}Api.js`, await app.utils.generTool.initApi(tablename, columns));
        
        //生成 dva model 
        await ctx.service.fs.createFolder(fpath + `/view/dva/${camelCaseTableName}Model.js`);
        await fs.writeFileSync(fpath + `/view/dva/${camelCaseTableName}Model.js`, await app.utils.generTool.initDvaModel(tablename, columns));
        
        //生成 视图层 list 列表 
        await ctx.service.fs.createFolder(fpath + `/view/pages/${tablename}/list.js`);
        await fs.writeFileSync(fpath + `/view/pages/${tablename}/list.js`, await app.utils.generTool.initList(tablename, columns));
        //add 新增
        await ctx.service.fs.createFolder(fpath + `/view/pages/${tablename}/add.js`);
        await fs.writeFileSync(fpath + `/view/pages/${tablename}/add.js`, await app.utils.generTool.initAdd(tablename, columns));
        //edit 编辑
        await ctx.service.fs.createFolder(fpath + `/view/pages/${tablename}/edit.js`);
        await fs.writeFileSync(fpath + `/view/pages/${tablename}/edit.js`, await app.utils.generTool.initEdit(tablename, columns));
        //detail 详情
        await ctx.service.fs.createFolder(fpath + `/view/pages/${tablename}/detail.js`);
        await fs.writeFileSync(fpath + `/view/pages/${tablename}/detail.js`, await app.utils.generTool.initDetail(tablename, columns));
    }

    /**
     * @param {提交的数据} quary 
     * @return 
     */
    async list(query) {
        const { ctx, app } = this;
        let { page, pageSize } = query;
        pageSize = pageSize || 10;
        page = page || 1;
        //查询列表
        let users = await ctx.model.query('SELECT * FROM sys_dept d WHERE d.deleted=:deleted LIMIT :offset, :limit',
            { replacements: { deleted: '0', offset: (page - 1) * pageSize, limit: pageSize * 1 }, raw: true, type: app.Sequelize.QueryTypes.SELECT });
        //查询总数
        let count = await ctx.model.query('SELECT count(*) as total FROM sys_dept d WHERE d.deleted=:deleted',
            { replacements: { deleted: '0' }, raw: true, type: app.Sequelize.QueryTypes.SELECT });

        return {
            list: users,
            total: count[0].total
        };
    }

    /**
     * @param {提交的数据} quary 
     * @return 
     */
    async settingCodeColumns(tableName, columnsValue, optUser) {
        const { ctx, app } = this;
        const uuid = require('node-uuid');
        //删除原代码配置
        let delRs = await ctx.model.SysGenColumn.destroy({
            where: {
                "table_name": tableName
            }
        });
        console.log("配置数组===", columnsValue)
        for (var i = 0; i < columnsValue.length; i++) {
            let creRs = await ctx.model.SysGenColumn.create({
                id: uuid.v1(),
                table_name: tableName,
                column_name: columnsValue[i].t_column_name,
                column_type: columnsValue[i].t_data_type,
                sort: columnsValue[i].t_ordinal_position,
                //字段描述
                column_comment: columnsValue[i].column_comment,
                //数据类型
                model_type: columnsValue[i].model_type,
                //数据长度
                model_long: columnsValue[i].model_long,
                //是否主键
                is_pk: columnsValue[i].is_pk,
                //是否新增
                is_add: columnsValue[i].is_add,
                //是否编辑
                is_edit: columnsValue[i].is_edit,
                //是否详情
                is_detail: columnsValue[i].is_detail,
                //是否列表展示
                is_list: columnsValue[i].is_list,
                //是否查询
                is_query: columnsValue[i].is_query,
                //是否必填
                is_required: columnsValue[i].is_required,
                //查询类型
                query_type: columnsValue[i].query_type,
                //控件类型
                html_type: columnsValue[i].html_type,
                //必要操作属性
                create_by: optUser,
                update_by: optUser,
                create_time: new Date(),
                update_time: new Date()
            });
            // console.log("保存结果", creRs);
        }

        return {
            code: 200,
            msg: "成功",
            data: {}
        }
    }

}

module.exports = GenService;